package com.bot.edu.applysystem.applycontract.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bot.edu.utils.AlipayConfig;
import com.bot.edu.utils.SnowFlake;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import com.bot.edu.applysystem.applycontract.entity.ApplyContract;
import com.bot.edu.applysystem.applycontract.service.IApplyContractService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 合同表
 * @Author: jeecg-boot
 * @Date:   2022-04-08
 * @Version: V1.0
 */
@Api(tags="合同表")
@RestController
@RequestMapping("/applycontract/applyContract")
@Slf4j
public class ApplyContractController extends JeecgController<ApplyContract, IApplyContractService> {
	@Autowired
	private IApplyContractService applyContractService;
	
	/**
	 * 分页列表查询
	 *
	 * @param applyContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "合同表-分页列表查询")
	@ApiOperation(value="合同表-分页列表查询", notes="合同表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ApplyContract>> queryPageList(ApplyContract applyContract,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ApplyContract> queryWrapper = QueryGenerator.initQueryWrapper(applyContract, req.getParameterMap());
		Page<ApplyContract> page = new Page<ApplyContract>(pageNo, pageSize);
		IPage<ApplyContract> pageList = applyContractService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param applyContract
	 * @return
	 */
	@AutoLog(value = "合同表-添加")
	@ApiOperation(value="合同表-添加", notes="合同表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ApplyContract applyContract) {
		//雪花算法随机生成ID
		String id = SnowFlake.getId();
		applyContract.setContractId(id);
		applyContractService.save(applyContract);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param applyContract
	 * @return
	 */
	@AutoLog(value = "合同表-编辑")
	@ApiOperation(value="合同表-编辑", notes="合同表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ApplyContract applyContract) {
		applyContractService.updateById(applyContract);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同表-通过id删除")
	@ApiOperation(value="合同表-通过id删除", notes="合同表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		applyContractService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同表-批量删除")
	@ApiOperation(value="合同表-批量删除", notes="合同表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.applyContractService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合同表-通过id查询")
	@ApiOperation(value="合同表-通过id查询", notes="合同表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ApplyContract> queryById(@RequestParam(name="id",required=true) String id) {
		ApplyContract applyContract = applyContractService.getById(id);
		if(applyContract==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(applyContract);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param applyContract
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ApplyContract applyContract) {
        return super.exportXls(request, applyContract, ApplyContract.class, "合同表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ApplyContract.class);
    }

	 /**
	  * 确认合同，修改合同状态
	  */
	 @PostMapping("updateContractState/{contractId}/{newStatus}")
	 public Result<String> updateContractState(@PathVariable String contractId,@PathVariable String newStatus){
		 UpdateWrapper<ApplyContract> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.lambda().eq(ApplyContract::getId,contractId);

		 ApplyContract applyContract = new ApplyContract();
		 applyContract.setContractState(newStatus);
		 boolean update = applyContractService.update(applyContract, updateWrapper);
		 if (update!=true){
			 return Result.error("确认失败");
		 }
		 return Result.ok("确认成功");
	 }

	 /**
	  *   添加：报名同意后生成合同
	  *
	  * @param applyName,applyId
	  * @return
	  */
	 @AutoLog(value = "合同表-生成")
	 @ApiOperation(value="合同表-生成", notes="合同表-生成")
	 @PostMapping(value = "/addContract/{userId}/{applyName}/{applyId}")
	 public Result<String> addContract(@PathVariable String userId,@PathVariable String applyName,@PathVariable String applyId) {
		 ApplyContract applyContract = new ApplyContract();
		 //合同编号
		 String id = SnowFlake.getId();
		 applyContract.setContractId(id);
		 //用户学生编号
		 applyContract.setUserId(userId);
		 //签订人
		 applyContract.setApplyName(applyName);
		 //报名编号
		 applyContract.setApplyId(applyId);
		 //合同金额
		 applyContract.setContractMoney(20000.0);
		 //缴费方式
		 applyContract.setContractPayment("0");
		 //签订时间
		 Date date = new Date();
		 applyContract.setSignedTime(date);
		 //生效时间
		 applyContract.setEffectiveTime(date);
		 ////失效时间，未来150天
		 Date date150 = new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000 * 150L);
		 applyContract.setFailureTime(date150);
		 applyContractService.save(applyContract);
		 return Result.OK("添加成功！");
	 }

     /**
      * 展示列表
      * @return
      */
     @GetMapping("/lists")
     public Result<?> lists(@RequestParam("stuId") String stuId) {
         QueryWrapper<ApplyContract> queryWrapper = new QueryWrapper<>();
         queryWrapper.lambda().eq(ApplyContract::getUserId, stuId);
         List<ApplyContract> list = applyContractService.list(queryWrapper);
         return Result.OK(list);
     }

     @GetMapping("/upstatus")
     public Result<?> upstatus(@RequestParam("contractId") String contractId,
                               @RequestParam("contractState") String contractState){
         ApplyContract applyContract = new ApplyContract();
         applyContract.setContractState(contractState);
         QueryWrapper<ApplyContract> queryWrapper = new QueryWrapper<>();
         queryWrapper.lambda().eq(ApplyContract::getContractId,contractId);
         applyContractService.update(applyContract,queryWrapper);
         return Result.OK("签订成功");
     }

     @GetMapping("/pay")
     public Result<?> pay(@RequestParam("contractId") String contractId){
         Result<Object> result = new Result<>();
         String pay=null;
         try {
             QueryWrapper<ApplyContract> queryWrapper = new QueryWrapper<>();
             queryWrapper.lambda().eq(ApplyContract::getContractId,contractId);
             ApplyContract contract = applyContractService.getOne(queryWrapper);
             //调用支付宝接口
             pay = applyContractService.pay(contract);
             result.setResult(pay);
             result.setSuccess(true);
         }catch (Exception e){
             result.setMessage("支付失败："+e.getMessage());
         }
         return Result.OK(pay);
     }

     @RequestMapping("/checkOrder")
     public Result<?> checkOrder(HttpServletRequest request) throws Exception{
         try {
             Map<String, String> params = new HashMap<String, String>();
             Map requestParams = request.getParameterMap();
             for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                 String name = (String) iter.next();
                 String[] values = (String[]) requestParams.get(name);
                 String valueStr = "";
                 for (int i = 0; i < values.length; i++) {
                     valueStr = (i == values.length - 1) ? valueStr + values[i]
                             : valueStr + values[i] + ",";
                 }
                 //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                 valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                 params.put(name, valueStr);
             }
             //验证信息是否真是[支付宝的公钥  去验证，验证签名(解码)]
             boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);

             if (signVerified) {
                 //如果信息验证通过  则修改订单状态为  已支付
                 String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"utf-8");
                 //String contractId = params.get("out_trade_no");
                 QueryWrapper<ApplyContract> queryWrapper = new QueryWrapper<>();
                 queryWrapper.lambda().eq(ApplyContract::getContractId,out_trade_no);
                 ApplyContract applyContract = applyContractService.getOne(queryWrapper);
                 applyContract.setContractState("3");
                 applyContractService.updateById(applyContract);
             }else {
                 return Result.error("支付失败");
             }
         }catch (Exception e){
             return Result.OK();
         }
         return Result.OK();
     }


 }
